package org.grow.auth.service;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.grow.auth.dao.BasicInfoRepository;
import org.grow.auth.entity.BasicInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Service;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.time.LocalDateTime;

/**
 * @Author: xwg
 * @CreateDate: 2021/10/13
 */

@Service
public class DefaultAuthSuccessHandler implements AuthenticationSuccessHandler {
    @Autowired
    private ObjectMapper objectMapper;
    @Autowired
    private BasicInfoRepository basicInfoRepository;
    @Override
    public void onAuthenticationSuccess(HttpServletRequest httpServletRequest,
                                        HttpServletResponse httpServletResponse,
                                        Authentication authentication) throws IOException, ServletException {
        System.out.println("登录成功:"+authentication.getPrincipal());
//        大有作为
        httpServletResponse.setStatus(200);
        String name = authentication.getName();
        BasicInfo basicInfo = basicInfoRepository.findByUsernameFk(name);
        httpServletResponse.getWriter()
                .println(objectMapper.writeValueAsString(basicInfo));
//        更新登录时间，为了下一次登录使用。
        basicInfo.setLastLoginTime(LocalDateTime.now());
        basicInfoRepository.save(basicInfo);




    }
}
